<template>
  <!-- 用户列表 -->
  <el-card class="user-list" style="margin: 20px;">
    <el-table :data="paginatedUsers" border style="width: 100%">
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="fullName" label="真实姓名"></el-table-column>
      <el-table-column prop="skills" label="特殊技能"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="电话号码"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
      <el-table-column prop="updatedAt" label="更新信息时间"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)" size="small">
            {{ row.status }}
          </el-tag>
          <!-- 审核按钮（仅限“未审核”状态） -->
          <el-button
            v-if="row.status === '未审核'"
            @click="approveUser(row)"
            size="small"
            style="margin-left: 10px;"
          >
            通过
          </el-button>
          <!-- 拒绝按钮（仅限“已审核”状态） -->
          <el-button
            v-if="row.status === '已审核'"
            @click="rejectUser(row)"
            size="small"
            type="danger"
            style="margin-left: 10px;"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增：去审核按钮 和 返回按钮 -->
    <div style="margin-top: 20px; text-align: right;">
      <el-button @click="showUnverifiedUsers" type="primary">
        去审核
      </el-button>
      <el-button @click="resetUserList" type="info" style="margin-left: 10px;">
        返回
      </el-button>
    </div>
    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserList, passStatus, rejectStatus } from '@/api/user'

// 用户列表数据
const users = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const paginatedUsers = ref([])
// 状态映射
const statusType = (status) => {
  switch (status) {
    case 1:
    case '已审核':
      return 'success';
    case 0:
    case '未审核':
      return 'warning';
    default:
      return '';
  }
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await getUserList();
    const rawData = Array.isArray(response?.data) ? response.data : [];

    const formattedUsers = rawData.map(user => ({
      userId: user.userId,
      username: user.username,
      fullName: user.fullName,
      skills: Array.isArray(user.skills) ? user.skills.map(s => s.skillName).join(', ') : '无', // 将技能数组转为逗号分隔的字符串
      email: user.email,
      phone: user.phone,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
      status: user.status === 0 ? '未审核' : '已审核'
    }))

    // 设置总数据
    users.value = formattedUsers;
    total.value = users.value.length;

    // 分页
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    paginatedUsers.value = users.value.slice(start, end);

  } catch (error) {
    console.error('获取用户数据失败:', error);
    users.value = [];
    paginatedUsers.value = [];
    total.value = 0;
    if(error.code == "ERR_NETWORK") {
      ElMessage.error('获取用户数据失败，请检查网络或稍后再试');
    } else if(error.response.status === 403) {
      ElMessage.error('无权限访问此页面，请重新登录');
    }
  }
}
// 分页切换
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchUsers()
}
// 审核用户
const approveUser = async (row) => {
  try {
    console.log('row', row);
    console.log('row.userId', row.userId);
    const response = await passStatus({ userId: row.userId });
    if (response.code === 200) {
      row.status = '已审核';
      ElMessage.success(`用户 ${row.username} 已通过审核`);
      await fetchUsers(); // 刷新数据
    } else {
      ElMessage.error('审核失败，请重试');
    }
  } catch (error) {
    console.error('审核用户失败:', error);
    ElMessage.error('审核失败，请检查网络或稍后再试');
  }
}

// 拒绝用户
const rejectUser = async (row) => {
  try {
    const response = await rejectStatus({ userId: row.userId });
    if (response.code === 200) {
      row.status = '未审核';
      ElMessage.warning(`用户 ${row.username} 已被拒绝`);
      await fetchUsers(); // 刷新数据
    } else {
      ElMessage.error('拒绝失败，请重试');
    }
  } catch (error) {
    console.error('拒绝用户失败:', error);
    ElMessage.error('拒绝失败，请检查网络或稍后再试');
  }
}

// 显示未审核用户
const showUnverifiedUsers = () => {
  try {
    // 更新分页数据为只显示未审核用户
    const unverified = users.value.filter(user => user.status === '未审核')
    
    // 更新总数据
    total.value = unverified.length
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    paginatedUsers.value = unverified.slice(start, end)
    
    ElMessage.success(`共找到 ${total.value} 个未审核用户`)
  } catch (error) {
    console.error('获取未审核用户时发生错误:', error)
    ElMessage.error('获取未审核用户失败，请重试')
  }
}

onMounted(() => {
  fetchUsers()
})

// 重置用户列表为显示所有用户
const resetUserList = () => {
  try {
    // 重置分页数据为完整用户列表
    total.value = users.value.length;
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    paginatedUsers.value = users.value.slice(start, end);

    ElMessage.success('已重置为显示所有用户');
  } catch (error) {
    console.error('重置用户列表时发生错误:', error);
    ElMessage.error('重置用户列表失败，请重试');
  }
};
</script>

<style scoped>
.user-list {
  margin: 20px;
  text-align: left;
}
</style>